package service

import (
	"dks-goweb/model"
	"dks-goweb/utils"
	"encoding/json"
	"sync"
)

func RefreshService(card string) model.DiagnosisResponse {
	var wg sync.WaitGroup
	results := make(chan model.RefreshBody, 3)
	// 请求体----------------------------------------------------------------
	requestBody, err := json.Marshal(model.CardRequest{Card: card})
	if err != nil {
		return model.DiagnosisResponse{Diagnosis: "json转换失败"}
	}
	urls := []string{
		"https://wx.88iot.net/iot/card/v2/diagnosisCardStatus",
		"https://wx.88iot.net/iot/card/v2/diagnosisEffective",
		"https://wx.88iot.net/iot/card/diagnosis",
	}

	for _, url := range urls {
		wg.Add(1)
		go startGoroutines(&wg, url, requestBody, results)
	}
	// 等待所有请求完成
	wg.Wait()
	close(results)

	// 收集所有结果
	var resultSlice []model.RefreshBody
	for result := range results {
		resultSlice = append(resultSlice, result)
	}
	response := model.DiagnosisResponse{}

	for _, res := range resultSlice {
		switch res.URL {
		case "https://wx.88iot.net/iot/card/v2/diagnosisCardStatus":
			response.DiagnosisCardStatus = res.Msg
		case "https://wx.88iot.net/iot/card/v2/diagnosisEffective":
			response.DiagnosisEffective = res.Msg
		case "https://wx.88iot.net/iot/card/diagnosis":
			response.Diagnosis = res.Msg
		}
	}

	return response
}

// 发送刷新请求帮助函数
func diagnosisHelper(url string, reqbody []byte) model.RefreshBody {
	diagnosis, err := utils.PostRequest(url, reqbody)
	if err != nil {
		return model.RefreshBody{Msg: "调用 " + url + "失败"}
	}
	var diagnosisStruct model.RefreshBody
	err = json.Unmarshal(diagnosis, &diagnosisStruct)
	if err != nil {
		return model.RefreshBody{Msg: "转换" + url + "失败"}
	}
	diagnosisStruct.URL = url
	return diagnosisStruct
}

func startGoroutines(wg *sync.WaitGroup, url string, reqbody []byte, results chan<- model.RefreshBody) {
	defer wg.Done()
	results <- diagnosisHelper(url, reqbody)

}
